<template>
    <div class="warehouseConfirmation">
        <van-form @submit="onSubmit">
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="stockCode" maxlength="25" label="库存编码"
                    v-model="queryParams.stockCode" required placeholder="请输入" :rules="[
                        {
                            required: true,
                            trigger: 'onBlur',
                            message: '请输入库存编码',
                        },
                        {
                            validator: validatorCode,
                            trigger: 'onChange',
                            message: '请输入正确的库存编码(汉字,字母,数字)',
                        },
                    ]" />
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="putNum" label="入库数量" required input-align="right" error-message-align="right">
                    <template #input>
                        <van-stepper v-model="queryParams.putNum" min="1" max="999" integer :before-change="onChange" />
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group inset>
                <van-field name="noticeTag" label="过期提醒" input-align="right" error-message-align="right">
                    <template #input>
                        <van-switch v-model="queryParams.noticeTag" size="18px" :active-value="1" :inactive-value="0" />
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group inset>
                <van-field v-model="queryParams.overdueTime" is-link readonly input-align="right"
                    error-message-align="right" name="datePicker" label="保质期至" placeholder="点击选择时间"
                    @click="showPicker = true" />
                <div class="overdueTime_hint">
                    <span>提示：</span>系统将在您选择的到期日发送该商品的消息提醒
                </div>
            </van-cell-group>
            <!-- <formNumberKeyboard :formRef="formRef" name="historyPrice" label="历史最低售价"
                v-model:keyValue="queryParams.historyPrice" placeholder="请输入" :rules="[
                    {
                        required: false,
                        trigger: 'onBlur',
                        message: '请输入历史最低售价',
                    },
                    {
                        validator: validatorPrice,
                        message: '请输入正确的历史最低售价',
                    },
                ]" extraKey="." /> -->
            <div class="image-title">
                请补充实拍图
            </div>
            <van-cell-group inset>
                <van-field name="商品图" label="" v-model="queryParams.stockImage">
                    <template #input>
                        <div class="value">
                            <div v-for="(item, index) in productImageList" :key="index" class="imgList">
                                <div class="loading_pic" v-if="!item.url">
                                    <van-loading type="spinner" size="20" />
                                </div>
                                <van-image v-if="item.url" :src="item.url" @click="enlargeImage(item.url)"></van-image>
                                <van-icon v-if="item.url" name="cross" color="#fff" @click.prevent="
                                    deleteImg(
                                        productImageList,
                                        index,
                                    )
                                    " />
                            </div>
                            <van-image :src="upload" v-if="productImageList.length < 5"
                                @click="postImage('shotImage', 5)" v-throttle:click></van-image>
                        </div>
                    </template>
                </van-field>
            </van-cell-group>
            <van-cell-group inset>
                <van-field input-align="right" error-message-align="right" name="inAuditRemark" label="备注"
                    maxlength="200" v-model="queryParams.inAuditRemark" placeholder="请输入"
                    @input="(e) => { forbidRule(e, 'inAuditRemark', 'emoji') }" />
            </van-cell-group>
            <van-button class="button" round block type="primary" native-type="submit" v-throttle:click
			:loading="loading"  loading-text="执行中..."
                v-if="buttonFlag">
                提交入库
            </van-button>
        </van-form>
        <van-popup v-model:show="showPicker" position="bottom">
            <van-date-picker @confirm="onConfirm" :min-date="new Date()" @cancel="showPicker = false" />
        </van-popup>
    </div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref, watch, onUnmounted } from 'vue';
import { getEnvValue } from "@/utils/index";
import { showImagePreview, showSuccessToast,showFailToast } from 'vant';
import { loginStore } from "@/store/login";
import { storeToRefs } from "pinia";
import { useRoute, useRouter } from 'vue-router';
import { pass } from '@/api/productHome/index'
import { handleImageUpdate } from '@/utils/handleImageUpdate';
// import formNumberKeyboard from "@/components/formNumberKeyboard/index.vue";
const route = useRoute();
const loading = ref(false)
const router = useRouter();
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
// const formRef = ref()
const buttonFlag = ref(true)
const showPicker = ref(false)
const onConfirm = ({ selectedValues }) => {
    queryParams.value.overdueTime = selectedValues.join('-')
    showPicker.value = false;
};
// 在组件挂载完成后添加事件监听器
onMounted(() => {
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
});
// 控制键盘弹出按钮得显示隐藏
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出
        buttonFlag.value = false
    } else {
        // 当软键盘收起
        buttonFlag.value = true
    }
})

// 步进器限制 阻止输入负数
const onChange = (value: string): any => {
    return new Promise((resolve) => {
        if (value !== '-') {
            resolve(true);
        }
    });
}

/** 商品id */
const id = computed(() => {
    return route.params.id;
});

/** 商品productsId */
const productsId = computed(() => {
    return route.query.productsId;
});


const store = loginStore();
const { token } = storeToRefs(store);
const upload = new URL("@/assets/home/upload.png", import.meta.url).href;
const queryParams = ref<any>({
    stockCode: '',
    putNum: 1,
    // historyPrice: '',
    stockImage: "",
    overdueTime: '',
    noticeTag: 0
})
const productImageList = ref<any[]>([]);

// 库存编码验证
const validatorCode = (value: string) => {
    if (/^[A-Za-z0-9\u4e00-\u9fa5]{1,25}$/.test(value)) {
        return true;
    } else {
        return false
    }
};


// 历史最低售价
// const validatorPrice = (val) => {
//     if (val) {
//         return /(^(?!0\d)([1-9]\d{0,8}(\.\d{1,2})?|0(\.\d{1,2})?)$)/.test(val)
//     } else {
//         return true
//     }
// }
// 提交
const onSubmit = async () => {
    const list = JSON.parse(JSON.stringify(queryParams.value));
    list.stockImage = getPicByfullPath(productImageList.value)
    list.productsId = productsId.value
    list.stockId = id.value

	
	loading.value = true
	try {
	    await pass(list)
	    showSuccessToast({ type: 'success', message: '入库成功' });
		loading.value = false
	    router.push({
	        path: '/addArehousingSuccess',
	        query: {
	            from: 'warehouseConfirmation'
	        }
	    })
	} catch (error) {
        if(error=='timeout'){
	    showFailToast('入库失败');
        }
	    loading.value = false
	}
	
}
/**
 * 图片全路径转半路径
 * @param list 
 */
const getPicByfullPath = (list: any[]) => {
    if (list.length > 0) {
        const updatedList = list.map((item: any) => {
            return item.url.split(getEnvValue("VITE_APP_PIC_URL"))[1];
        });
        return updatedList.join(',');
    } else {
        return '';
    }
}
/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
/** 删除 */
const deleteImg = (list: any, index: number) => {
    list.splice(index, 1);
};
/** uniapp端上传图片 */
const postImage = (name: string, count: number) => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "img",
            count: count,
            name: name,
            url: getEnvValue("VITE_APP_UPLOAD_API") + '/resource/oss/upload',
            header: {
                Authorization: `Bearer ${token.value}`,
                clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
            },
        },
    });
};
// 输入事件、禁用规则
const forbidRule = (e: any, key: string, type: string | null) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        queryParams.value[key] = e.target.value.replace(
            /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi,
            '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        queryParams.value[key] = e.target.value.replace(
            /\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi,
            '')
    }
}
/** uniapp端回传 */
(window as any).msgFromUniapp = function (arg) {
    const imageLists = {
        shotImage: productImageList.value,
    };

    const maxCounts = {
        shotImage: 5,
    };

    const imageList = imageLists[arg.name];
    const maxCount = maxCounts[arg.name];

    handleImageUpdate(imageList, arg, maxCount);

}
</script>
<style lang="less" scoped>
.warehouseConfirmation {
    width: 100%;
    height: calc(100vh - 90px);
    background: #F6FAFF;
    box-sizing: border-box;
    padding: 10px;

    :deep(.van-form) {
        width: 100%;
        height: 100%;
        background-color: #fff;
        position: relative;
    }

    :deep(.van-cell-group--inset) {
        margin: 0 !important;
    }

    .image-title {
        font-weight: 400;
        font-size: 14px;
        color: #1a1b1c;
        background-color: #fff;
        padding-left: 15px;
    }

    .button {
        position: absolute;
        bottom: 20px;
    }

    .value {
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        .imgList {
            position: relative;

            .loading_pic {
                width: 90px;
                height: 90px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            :deep(.van-image__img) {
                margin-right: 5px;
            }

            :deep(.van-icon) {
                position: absolute;
                top: 0;
                z-index: 100;
                right: 4px;
                font-size: 10px;
                height: 15px;
                width: 15px;
                background-color: #000;
                border-bottom-left-radius: 16px;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            :deep(.van-icon-cross:before) {
                margin: 0 0 1px 2px;
            }
        }

        :deep(.van-image__img) {
            width: 77px;
            height: 77px;
        }
    }
}

.overdueTime_hint {
    padding-left: 15px;
    margin: 10px 0;
    color: #ccc;

    span {
        color: #F56C6C;
        font-weight: 900;
    }
}
</style>